package userserv

import (
	"codedef"
	"gentk"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"rhelper"
)

func verifyAccount(w http.ResponseWriter, r *http.Request) bool {
	var account = r.Header.Get("account")
	var password = r.Header.Get("password")
	if account == "" {
		log.Println("verifyAccount err, need fill account")
		replyError(w, codedef.ERR_ACCOUNT_NEED)
		return false
	}

	if password == "" {
		log.Println("verifyAccount err, need fill password")
		replyError(w, codedef.ERR_PASSWORD_NEED)
		return false
	}

	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	p, err := redis.String(rconn.Do("HGET", rhelper.AccountHash+account, "password"))
	if err != nil {
		log.Println("verifyAccount err:", err)
		replyError(w, codedef.ERR_DATABASE)
		return false
	}

	if p == "" {
		log.Println("verifyAccount err, account not exist")
		replyError(w, codedef.ERR_ACCOUNT_NOT_EXIST)
		return false
	}

	if p != password {
		log.Println("verifyAccount err, password not match")
		replyError(w, codedef.ERR_PASSWORD_NOT_MATCH)
		return false
	}

	return true
}

func onLogin(w http.ResponseWriter, r *http.Request) {
	var account = r.Header.Get("account")
	var password = r.Header.Get("password")

	if verifyAccount(w, r) == false {
		return
	}

	log.Printf("login, account:%s, password:%s\n", account, password)

	var tk = gentk.GenTK(account)
	log.Printf("login, tk:%s\n", tk)

	w.Header().Set("Content-Type", "text/plain")
	w.Header().Set("tk", tk)
	w.Write([]byte(tk))
}

func init() {
	myMux.muxHandlers.HandleFunc("/login", onLogin)
	myMux.ignoreToken["/login"] = true
}
